﻿using Microsoft.EntityFrameworkCore;

namespace CommonInitializer
{
    /// <summary>
    /// 提供创建 DbContextOptionsBuilder 实例的静态类
    /// </summary>
    public static class DbContextOptionsBuilderFactory
    {
        /// <summary>
        /// 创建并配置 DbContextOptionsBuilder 实例
        /// </summary>
        /// <typeparam name="TDbContext">要配置的 DbContext 类型</typeparam>
        /// <returns>配置好的 DbContextOptionsBuilder 实例</returns>
        public static DbContextOptionsBuilder<TDbContext> Create<TDbContext>(string? connStr = null)
            where TDbContext : DbContext
        {
            if(connStr == null)
            {
                // 从环境变量中获取 数据库连接字符串
                connStr = Environment.GetEnvironmentVariable("DefaultDB:ConnStr");
            }
            else
            {
                // 手动指定 数据库连接字符串
                //string connStr = "Data Source=.;Initial Catalog=YouzackVNextDB;User ID=sa;Password=dLLikhQWy5TBz1uM;";
            }

            // 创建 DbContextOptionsBuilder 实例
            var optionsBuilder = new DbContextOptionsBuilder<TDbContext>();

            // 将连接字符串应用于配置 DbContextOptions，以连接到 SQL Server 数据库
            optionsBuilder.UseSqlServer(connStr);

            // 返回配置好的 DbContextOptionsBuilder 实例
            return optionsBuilder;
        }
    }
}